import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'next/router';
import LazyLoad from 'react-lazyload';
import { Grid, ListView, Icon, NavBar, Toast } from 'antd-mobile';
import { observer, Provider } from 'mobx-react';
import { utilDecoding, utilEncoding } from '../tools/utils';

import HeadC from '../src/components/layout/head';
import FooterC from '../src/components/layout/footer';
import CustomSearchBar from '../src/containers/customSearchBar';
import CustomCarousel from '../src/containers/customCarousel';
import SingleItem from '../src/components/singleItem';

import { getRequest } from '../tools/requests';
import store from '../store';

import './index.css';

const NUM_ROWS = 20;
let pageIndex = 0;

function genData(pIndex = 0) {
  const dataBlob = {};
  for (let i = 0; i < NUM_ROWS; i++) {
    const ii = (pIndex * NUM_ROWS) + i;
    dataBlob[`${ii}`] = `row - ${ii}`;
  }
  return dataBlob;
}


function MyListViewBody(props, gridData) {
  return (
    <div className="am-list-body cus-am-list">
			<Grid 
				data={props.gridData} 
				columnNum={4}
				hasLine={false}
				// itemStyle={{ paddingBottom: '0rem' }}
				renderItem={dataItem => (
					<div className="grid-block" onClick={() => Router.push({pathname: dataItem.name == '特价' ? '/categoriesNoNav' :'/categories', query: {cateName: dataItem.name, cateId: dataItem.id}})}>
						<LazyLoad>
							<img src={dataItem.category_ico} alt="" />
						</LazyLoad>
						<div>
							<span>{dataItem.name}</span>
						</div>
					</div>
				)}
			/>
      { props.children }
    </div>
  );
}

@observer
class HomePage extends React.Component {
	static async getInitialProps({query}) {
		let firstCategories, carouselData, listQueCate;
		/*
		 * 这里首先从路由中获取topcate和subcate，如果路由中没有配置然后从后台接口中获取，后台没有配置再获取默认值
		 */
		let routeQueCate = JSON.parse( utilDecoding(query.cate) );
		if (!!!routeQueCate || (routeQueCate && !!!routeQueCate.topcate && !!!routeQueCate.subcate)) {
			const fetchListQueCate = await getRequest('front_end_config/', {business: "home"})
			if (fetchListQueCate.data) listQueCate = JSON.parse(fetchListQueCate.data.content);
		}

    const fetchCategory = await getRequest('get_primary_classify/')
    if (fetchCategory) firstCategories = fetchCategory; 

    const fetchCarouseData = await getRequest('get_home_carousel/')
		if (fetchCarouseData) carouselData = fetchCarouseData
		
		// 从后台获取首页请求的类别
		let topcate = (routeQueCate && routeQueCate.topcate) ? routeQueCate.topcate : (listQueCate && listQueCate.topcate) ? listQueCate.topcate : "热销";
		let subcate = (routeQueCate && routeQueCate.subcate) ? routeQueCate.subcate : (listQueCate && listQueCate.subcate) ? listQueCate.subcate : "女装";
		const fetchGoodsLists = await getRequest('goods_list/', {page: 1, page_size: NUM_ROWS, topcate, subcate})
		let goodsLists = fetchGoodsLists.data || []
		return {
			title: 'coupon',
			description: '',
			links: '',
			ogImage: '',
			gridData: firstCategories,
			goodsLists,
			carouselData: carouselData,
			queCate: routeQueCate || listQueCate
		}
	}
	constructor(props) {
		super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    this.state = {
      dataSource,
			height: 0,
			appHeight: 0,
			goodsLists: this.props.goodsLists,
			isLoading: false,
			isMore: false,
			queCate: this.props.queCate
			
    };
	}
	componentDidMount() {
		this.rData = genData();
    this.setState({
			dataSource: this.state.dataSource.cloneWithRows(this.rData),
			goodsLists: this.props.goodsLists,
			isLoading: false
		});
	}

 	async onEndReached(event) {
		if (this.state.isNoMore) {
      return false;
		}
		this.setState({isLoading: true});
		let pageAdd = ++pageIndex;
		pageAdd == 1 && (pageAdd = 2);
		let topcate = this.state.queCate && this.state.queCate.topcate ? this.state.queCate.topcate : "热销";
		let subcate = this.state.queCate && this.state.queCate.subcate ? this.state.queCate.subcate : "女装";
		const result = await getRequest('goods_list/', {page: pageAdd, page_size: NUM_ROWS, topcate, subcate});
    if (result.data) {
      this.rData = { ...this.rData, ...genData(pageAdd) };
      this.setState({
        goodsLists: result.data,
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
      });
    }else {
      this.setState({
        isLoading: false,
        goodsLists: [],
        noMore: true
      })
      Toast.fail(result.msg, 1);
    }
	}

	handleClickSearch() {
		Router.push('/search');
	}

	render() {
		const { title, description, links, ogImage } = this.props;
		const { goodsLists } = this.state;
		const row = (rowData, sectionID, rowID) => {
      let indexID = rowID > 20 ? rowID % 20 === 0 ? 19 : (rowID % 20) - 1 : rowID;
      let objItem = goodsLists[indexID] ? (
        <SingleItem key={rowID} item={goodsLists[indexID]}></SingleItem>
      ) : null;
      return objItem
    };
		return (
			<Provider>
				<div className="app-block">
					{/* html 头部信息 */}
					<HeadC 
						title={title} 
						description={description}
						links={links}
						ogImage={ogImage}
					></HeadC>
					{/* 头部 */}
					{/* <NavBar
						mode="light"
						style={{color: '#fa4d47', zIndex: 999}}
						className="detail-nav-block"
					>
						粉丝福利购
					</NavBar> */}

					{/* 搜索框 */}
					{/* <CustomSearchBar isHomePage={true} /> */}
					<div className="search-nav-block" onClick={this.handleClickSearch}>
						<div>
							<Icon type="search" size="xs" />
							<span>在此键入要查询的商品</span>
						</div>
					</div>

					{/* 轮播图 */}
					<div className="carousel-block">
						<CustomCarousel carouselData={this.props.carouselData} />
					</div>


					{/* 列表 */}
					{
						goodsLists && goodsLists.length > 0 ? (
							<ListView
								ref={el => this.lv = el}
								dataSource={this.state.dataSource}
								renderFooter={() => (<div style={{ padding: '15px', textAlign: 'center' }}>
									{this.state.isLoading ? <Icon type="loading" /> : '已经到最底部了...'}
								</div>)}
								renderRow={row}
								renderBodyComponent={() => <MyListViewBody gridData={this.props.gridData} />}
								className="am-list"
								pageSize={4}
								useBodyScroll
								onScroll={() => { console.log('scroll'); }}
								scrollRenderAheadDistance={500}
								onEndReached={this.onEndReached.bind(this)}
								onEndReachedThreshold={8}
								// style={{marginTop: '46px'}}
							/>
						) : (
							<div
								style={{marginTop: '100px', color: '#999', textAlign: 'center', marginTop: '50px'}}
							> 维护中，请稍等片刻.... </div>
						)
					}
					<FooterC src="../static/images/police.png" />
				</div>
			</Provider>	
		)
	}
}

export default HomePage;